package com.example.iot.service.ts.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.example.iot.entity.dto.TsData;
import com.example.iot.entity.id.EntityId;
import com.example.iot.entity.id.EntityIdFactory;
import com.example.iot.entity.id.EntityType;
import com.example.iot.entity.po.TaosTsData;
import com.example.iot.mapper.taos.Demo1Mapper;
import com.example.iot.service.ExecutorBaseService;
import com.example.iot.service.ts.TimeSeriesService;
import com.example.iot.service.websocket.SubscriptionService;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.taosdata.jdbc.TSDBDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author ChenXiangpeng
 */
@DS("taos")
@Service
public class TimeSeriesServiceImpl extends ExecutorBaseService implements TimeSeriesService {
    @Autowired
    private SubscriptionService subscriptionService;
    @Autowired
    private Demo1Mapper demo1Mapper;

    @Override
    public void save(String deviceId, TsData data) {
        // todo 保存时序数据
        // todo 可以异步
        TaosTsData taosTsData = new TaosTsData(System.currentTimeMillis(), data.getValue());
        demo1Mapper.insert(taosTsData);
        subscriptionService.onTimeSeriesUpdate(EntityIdFactory.getByTypeAndUuid(EntityType.DEVICE, deviceId), data);
    }

    @Override
    public ListenableFuture<List<TsData>> getAllLatest(String entityId, Executor executor) {
        return Futures.submit(() -> {
            return Lists.newArrayList(new TsData(1231413413, "123"),
                    new TsData(1231413414, "123"),
                    new TsData(1231413415, "124"),
                    new TsData(1231413416, "125"),
                    new TsData(1231413417, "1278"));
        }, executor);
    }

}
